package com.example.testapplication;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Handler2Activity extends ApplicationActivity{
    public static final int DOWNLOAD_MESSAGE_CODE = 100001;
    private static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002;
    Handler mHandler;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler2);

        ProgressBar progressBar = (ProgressBar) findViewById(R.id.handler_bar);

        /**
         * 主线程 http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk
         * 点击按键
         * 发起下载
         * 开启子线程做下载
         * 下载完成后通知主线程
         * 主线程更新进度条
         * **/
        findViewById(R.id.handler_btn2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        download("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk");

                    }
                }).start();


            }
        });
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                super.handleMessage(msg);

                switch (msg.what){
                    case DOWNLOAD_MESSAGE_CODE:
                        progressBar.setProgress((Integer) msg.obj);
                        break;
                }
            }
        };
    }

    private void download(String appUrl) {

        try {
            URL url = new URL(appUrl);
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            // 获取文件的总长度
            int contentLength = urlConnection.getContentLength();

            String downloadFolderName = Environment.getExternalStorageDirectory() +
                    File.separator + "imooc" + File.separator;

            File file = new File(downloadFolderName);
            if(!file.exists()){
                file.mkdir();
            }
            String fileName = downloadFolderName + "imooc.apk";
            File apkFile = new File(fileName);
            if(apkFile.exists()){
                apkFile.delete();
            }

            int downloadSize = 0;

            byte[] bytes = new byte[1024];
            int length = 0;
            OutputStream outputStream = new FileOutputStream(fileName);
            while ((length = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,length);
                downloadSize += length;

                // 更新UI
                Message message = Message.obtain();
                message.obj = downloadSize * 100 / contentLength;
                message.what = DOWNLOAD_MESSAGE_CODE;
                mHandler.sendMessage(message);
            }
            inputStream.close();
            outputStream.close();

        }catch (MalformedURLException e){
            // 发送失败的消息
            Message message = Message.obtain();
            message.what = DOWNLOAD_MESSAGE_FAIL_CODE;
            mHandler.sendMessage(message);

            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
